#include <stdio.h>
#include <stdlib.h>
#include "ask_encode.h"
#include "format.h"
#include "utils.h"

int main(int argc,char **argv)
{
	if(argc!=3)
	{
		fprintf(stderr,"Usage: %s input.dat output.au\n",argv[0]);
		exit(1);
	}

	FILE *in=open_file(argv[1],"rb",stdin,"Couldn't open file \"%s\".\n");

	fseek(in,0,SEEK_END);
	int length=ftell(in);
	fseek(in,0,SEEK_SET);

	u_int8_t bytes[length];
	fread(bytes,1,length,in);
	if(in!=stdin) fclose(in);

	check_errors(bytes,length,argv[1],1);

	FILE *out=open_file(argv[2],"wb",stdout,"Couldn't create file \"%s\".\n");

	struct ask_encoder ask;
	init_ask_encoder(&ask,bytes,length,8192,1024);

	write_bigendian_long(0x2e736e64,out);
	write_bigendian_long(24,out);
	write_bigendian_long(total_ask_sample_count(&ask),out);
	write_bigendian_long(2,out); // eight-bit linear PCM
	write_bigendian_long(8192,out);
	write_bigendian_long(1,out);

	while(!is_ask_done(&ask))
	{
		int numsamples=1024;
		int16_t samples[numsamples];

		int actual=request_ask_output(&ask,samples,numsamples);

		for(int i=0;i<actual;i++) fputc((samples[i]>>8)&0xff,out);
	}

	if(out!=stdout) fclose(out);
}
